﻿namespace Commands
{
    using System;
    using System.Windows;
    using System.Windows.Threading;

    /// <summary>
    /// Enables various advanced method execution options.
    /// </summary>
    public static class Execute
    {
        /// <summary>
        /// Create a <see cref="DelegatingCommandBuilder"/> for the action.
        /// </summary>
        /// <param name="action">The method to execute.</param>
        /// <returns>The builder</returns>
        public static DelegatingCommandBuilder AsCommand(Action<object> action)
        {
            return new DelegatingCommandBuilder(action);
        }

        /// <summary>
        /// Create a <see cref="DelegatingCommandBuilder"/> for the action.
        /// </summary>
        /// <param name="action">The method to execute.</param>
        /// <returns>The builder</returns>
        public static DelegatingCommandBuilder AsCommand(Action action)
        {
            return new DelegatingCommandBuilder(p => action());
        }

        /// <summary>
        /// Executes the backgroundAction on a background thread.
        /// </summary>
        /// <param name="backgroundAction">The action.</param>
        public static void OnBackgroundThread(Action backgroundAction)
        {
            if (Application.Current != null)
                backgroundAction.BeginInvoke(null, null);
            else backgroundAction();
        }

        /// <summary>
        /// Executes the backgroundAction on a background thread.
        /// </summary>
        /// <param name="backgroundAction">The action.</param>
        /// <param name="uiCallback">The UI callback.</param>
        public static void OnBackgroundThread(Action backgroundAction, Action uiCallback)
        {
            if (Application.Current != null)
            {
                backgroundAction.BeginInvoke(
                    r => OnUIThread(uiCallback),
                    null
                    );
            }
        }

        /// <summary>
        /// Executes the action on the UI thread.
        /// </summary>
        /// <param name="action">The action.</param>
        public static void OnUIThread(Action action)
        {
            if (Application.Current != null)
            {
                Application.Current.Dispatcher.Invoke(
                    DispatcherPriority.Send,
                    action
                    );
            }
        }
    }
}